package com.offcn.seckill.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Configuration
public class FeignConfig implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        try {
            //获取request 中的相关变量
            //包含请求头和请求参数
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

            if (attributes!=null){
                HttpServletRequest request = attributes.getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();

                if (headerNames!=null){
                    while (headerNames.hasMoreElements()){
                        String key = headerNames.nextElement();
                        String value = request.getHeader(key);
                        requestTemplate.header(key,value);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
